<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\home\controller;


use app\wechat\service\FansService;
use controller\BasicAdmin;
use service\DataService;
use service\NodeService;
use service\ToolsService;
use service\CalService;
use service\WechatService;
use think\App;
use think\Db;
use think\facade\Cache;
use service\WyismsService;


/**
 * 生日填写
 * @author caicai
 *
 *
 *
 */
class Index extends HomeBasic
{

    /**
     * 前端展示
     */
    /**
     * @return \think\App
     */
    public function index()
    {
        $openid = Cache::get('userInfo')['openid'];//微信ID
        // 用户信息验证
        $user = Db::name('WechatFans')->where(['openid' => $openid])->find();
        return json_encode($user);
    }

    /**
     * 批量导入好友生日
     *
     */

    public function addFriend(){
        // 输入数据效验
        $data = [
            'nickname' => $this->request->post('nickname', null),
            'birthday' => $this->request->post('birthday', ''),
            'sex' => $this->request->post('sex', ''),//微信ID
            'appid' => sysconf('mini_appid')
        ];
        $userinfo = Cache::get('userInfo');
        //新增到 WechatFans
        $data['constellation'] = ToolsService::get_constellation($data['birthday']);// 星座
        $friend_id = Db::name('WechatFans')->insertGetId($data);//新增到表格

        $friendArr = ['friend_id' => $friend_id, 'user_id' => $userinfo['id']];
        Db::name('WechatFansRelation')->insert($friendArr);

        return json_encode(['code'=>100]);
    }

    /**
     * 生日信息完善，同意入口验证 是否登录
     *备用
     * 前段接口
     * url
     *
     * http://www.caicai.com/ThinkAdmin/index.php/home.html
     */
    public function save()
    {
        // 输入数据效验
        $data = [
            'nickname' => $this->request->post('nickname', null),
            'birthday' => $this->request->post('birthday', ''),
            'openid' => $this->request->post('openid', ''),//微信ID
            'sex' => $this->request->post('sex', ''),//微信ID
            'friend_id' => $this->request->get('friend_id'),//推荐人ID
            'appid' => sysconf('mini_appid')
        ];
        // 用户信息验证
        $user = Db::name('WechatFans')->where(['openid' => $data['openid'], 'appid' => $data['appid']])->find();
        $user_id = $user['id'];

        if ($user) {
            $updateArr = ['nickname' => $data['nickname'], 'birthday' => $data['birthday'], 'sex' => $data['sex'],
                'constellation' => ToolsService::get_constellation($data['birthday'])];
            $where = ['id' => $user_id];
            Db::name('WechatFans')->where($where)->update($updateArr);
            // 更新生日信息
        }
        // 是否有推荐人ID，判断是否存在-->没有的【新增记录】
        //$CACHE_openid = Cache::get($data['openid']); //是否存在
        if (isset($data['friend_id'])) {
            $friendArr = ['friend_id' => Cache::get('userInfo')['id'], 'user_id' => $data['friend_id']];
            Db::name('WechatFansRelation')->insert($friendArr);
        }

        // 推送消息
        $tempid = 'cUFOrEM6E99CFHs0Eu8OPxzqOcmCJQrh4XcKe2mksU8';
        $form_id = $this->request->post('formId');
        $message = [
            'keyword1' => ['value'=>"aaa"],
            'keyword2' => ['value'=>"bb"],
            'keyword3' => ['value'=>"cc"],
        ];
        parent::templateSend($data['openid'],$form_id,$tempid,$message);

        return json_encode(['code'=>100]);
    }





    /**
     * 验证码发送
     */
    public function sendSms(){
        $phone = $this->request->post('phone');
        $AppKey = '5fee366fb8e4b5e55f79807ee101afbd';
        $AppSecret = '36004a8b1cdf';
        $p = new WyismsService($AppKey,$AppSecret,'curl');

        $code = ToolsService::generateRandomString();
        Cache::set('CACHE_PHONE_'.$phone,$code,60*5); // 五分钟
        $res = $p->sendSMSTemplate('3031261',array($phone),array($code));
        return json_encode(array_merge($res,['iscode'=>$code]));
    }

    /**
     * 验证校验码
     * @return string
     */
    public function validateCode(){
        $phone = $this->request->post('phone');
        $code = $this->request->post('code');
        $origin_code =  Cache::get('CACHE_PHONE_'.$phone);
        if (!$origin_code) {
            return json_encode(['code' => 101, 'mgs'=>'校验码失效']);
        }
        if ($origin_code==$code) {
            //更新用户资料
            $userInfo = Cache::get('userInfo');
            $userInfo['phone'] = $phone;

            $updateArr = ['phone' => $phone];
            $where = ['id' => $userInfo['id']];
            Db::name('WechatFans')->where($where)->update($updateArr);
            Cache::set('userInfo',$userInfo,12*60*60);//更新手机号资料

            return json_encode(['code' => 100, 'mgs'=>'验证成功']);
        }else {
            return json_encode(['code' => 102, 'mgs'=>'校验码错误']);
        }
    }

    /**
     * 获取明星资料
     * 和排行榜
     */
    public function getStar(){
        $id = $this->request->post('starid','');
        $data = Db::table('wechat_star')
                ->alias('s')
                ->leftJoin('wechat_star_like l','s.id = l.starid')
                ->where(['s.id' => $id])
                ->field(['s.*','l.follownum','l.likenum'])
                ->select();
        // 整数处理
        foreach ($data as &$item) {
            $item['follownum'] = (int) $item['follownum'];
            $item['likenum'] = (int) $item['likenum'];
        }

        $top = $this->getStarLog($id,1);
        //获取点赞记录排行榜
        return json_encode(array_merge(['star'=>current($data),'top'=>$top]));
    }

    /**
     * 获取明星排行榜
     * 点赞和关注排行
     */
    public function getStarTop(){

        $type = $this->request->post('type','1');
        $db = Db::name('wechatStarLike')
                ->limit(10);
        if ($type == 1) {
            $data = $db->order('likenum desc')->select();
        } else {
            $data = $db->order('follownum desc')->select();
        }
        // 整数处理
        foreach ($data as &$item) {
            $item['follownum'] = (int) $item['follownum'];
            $item['likenum'] = (int) $item['likenum'];
        }
        return json_encode($data);
    }

    /**
     * 关注或者点赞给某个明星
     */
    public function getLike(){
        $id = $this->request->post('starid','');
        $type = $this->request->post('type','1');
        $db = Db::name('wechatStarLike')->where(['starid' =>$id ]);
        if ($type==1) {
            $db->setInc('likenum');
        } else {
            $db->setInc('follownum');
        }
        $insert = ['starid' => $id, 'type' => $type, 'userid' => Cache::get('userInfo')['id']];
        Db::name('wechatStarLikeLog')->insert($insert);

        $data = $db->find();
        return json_encode($data);
    }

    /**
     * 获取明星点赞记录
     * @param int $id 明星ID
     * @param int $type 类型，点赞还是关注人数，默认1
     */

    private function getStarLog($id, $type = 1)
    {
        //先查询10条记录最高用户
        $usrdata = Db::name('wechatStarLikeLog')
            ->where(['starid' => $id, 'type' => $type])
            ->field(['count(userid) as c', 'userid'])
           // ->group('count(userid)')
            ->limit(10)->order('c decs')->select();

        $user_ids = array_column($usrdata, 'userid');
        empty($user_ids) && $data = [];
        $data = Db::name('wechatFans')->whereIn('id', $user_ids)->select();

        foreach ($data as &$item) {
            foreach ($usrdata as $v) {
                if ($item['id']==$v['userid']) {
                    $item['c'] = $v['c'];
                }
            }
        }
        return $data;
    }

    /**
     * 根据生日信息，获取
     *
     * 性格密码
     */
    public function getNature(){
        $birthday = $this->request->post('birthday') ? $this->request->post('birthday'):date('Y-m-d');
        $birthday = date('m-d',strtotime($birthday));
        $data = Db::name('BirthdayNature')->where(['birthday'=>$birthday])->find();
        return json_encode($data);
    }

}




